<template>
  <div>
    <!-- 标题 -->
    <mu-base-title title="编辑签约信息" />

    <!-- 居民信息 -->
    <div class="mu-small-title ">居民信息</div>
    <mu-resident-info ref="muResidentInfoRef" v-model:form-data="residentData" @updateSign="updateSign" />

    <!-- 签约信息 -->
    <div class="mu-small-title ">签约信息</div>
    <mu-info ref="muInfoRef" v-model:form-data="signDetailData" />

    <!-- 按钮 -->
    <div class="mu-btn-box-top-style">
      <el-button type="primary" @click="onUpdate">确认</el-button>
      <el-button @click="$router.back()">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { updateResidentApi } from '@/api/resident';
import { getSignDetailApi, updateSignsApi } from '@/api/sign';
import { onMounted, ref, useTemplateRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const muResidentInfoRef = useTemplateRef('muResidentInfoRef');
const muInfoRef = useTemplateRef('muInfoRef');

const route: any = useRoute();
const router: any = useRouter();

// 签约详情 数据
const signDetailData: any = ref({});
// 居民信息 数据
const residentData: any = ref({});



onMounted(() => {
  getSignDetail(route.params._id);
})



// 事件：确认修改按钮点击
const onUpdate = async () => {
  // 表单验证是否通过
  const muResidentInfoResult = await muResidentInfoRef.value?.onSubmit();
  const muInfoResult = await muInfoRef.value?.onSubmit();
  if (muResidentInfoResult && muInfoResult) {
    // 修改用户数据
    updateResident();
  }
};

// 请求：修改用户信息
const updateResident = async () => {
  const res = await updateResidentApi({
    ...residentData.value
  });
  if (res.code == 200) {
    ElMessage.success('居民信息修改成功');
    updateSign();
  } else if (res.code == 500) {
    updateSign();
  } else {
    ElMessage.error(res.message);
  }
}

// 请求：修改 签约信息
const updateSign = async () => {
  const res = await updateSignsApi({
    ...signDetailData.value,
    residentId: residentData.value._id
  });
  if (res.code == 200) {
    ElMessage.success('签约信息修改成功');
    router.back();
  } else {
    ElMessage.error(res.message);
  }
};

// 请求：获取 签约详情
const getSignDetail = async (_id: string) => {
  const res = await getSignDetailApi({ _id });
  // console.log(res);
  if (res.code == 200) {
    residentData.value = res.data.residentId ?? {};
    signDetailData.value = {
      ...res.data
    };
  }
};
</script>

<style scoped lang="scss">
.none-text {
  color: rgb(241, 127, 127);
  font-size: 14px;
  font-weight: bold;
}
</style>